from flask import Flask
from flask_sqlalchemy import SQLAlchemy

"""

    flask-sqlalchemy 介绍与安装

     pip install -U Flask-SQLalchemy
    源码安装 python setup.py install

    安装mysql驱动依赖
    pip install mysqlclient / brew install mysql-client

    flask-sqlalchemy配置
    数据库URI SQLALCHEMY_DATABASE_URI
    统一资源标识符 是一个用于标识某一互联网资源名称的字符串

    MySQL数据库URI参数格式
    mysql://scott:tiger@localhost/mydatabase
    数据库类型://用户:密码@主机/数据库名称
    
    多个数据库的支持
    SQLALCHEMY_BINDS = {
        'db1': 'mysqldb://localhost/users',
        'db2': 'sqlite:////path/to/appmeta.db'
    }
    
    绑定到Flask对象
    db = SQLAlchemy(app)
    
    ORM模型创建
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
    指定表名称
        _tablename_ = 'user'
    
    手动创建数据库
    创建表
        >>> db.create_all(bind='db1')
    删除表
        >>> db.drop_all()
    
"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/test_flask'
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'weibo_user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), nullable=False)
    password = db.Column(db.String(256), nullable=False)
    birth_date = db.Column(db.DateTime, nullable=True)
    age = db.Column(db.Integer, default=0)

class UserAddress(db.Model):
    """用户地址"""
    __tablename__ = 'weibo_user_addr'
    id = db.Column(db.Integer, primary_key=True)
    addr = db.Column(db.String(256), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('weibo_user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('address', lazy=True))

"""
user = User()
user.address
addr = UserAddress()
addr.user
"""

with app.app_context():
    db.drop_all()
    db.create_all()
    print("表创建成功！")

if __name__ == '__main__':
    app.run(debug=True)